<?php
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

class wx_pay extends CI_Controller
{
    function ddzf($bill_id)
    {
        $this->db->select('state');
        $q = $this->db->get_where('bill', array('bill_id' => $bill_id));
        $bill = $q->row_array(0);
        if ($bill['state'] == 0) {
            include_once(FCPATH . APPPATH . 'third_party' . DS . 'wx' . DS . "WxPayPubHelper.php");
            //判断是否已经支付
            $orderQuery = new OrderQuery_pub();
            $orderQuery->setParameter("out_trade_no", $bill_id);
            $orderQueryResult = $orderQuery->getResult();
            //商户根据实际情况设置相应的处理流程,此处仅作举例
            if ($orderQueryResult["return_code"] == "FAIL") {
                $this->load->view('co/ts', array('msg' => "通信出错：" . $orderQueryResult['return_msg'] . "<br>"));
            } elseif ($orderQueryResult["result_code"] == "FAIL") {
                $this->_do_pay($bill_id);
            } else {
                if ($orderQueryResult['trade_state'] == 'NOTPAY') {
                    $this->_do_pay($bill_id);
                } else {
                    //已经支付成功
                    $this->load->view('pub/ts', array('msg' => '账单已支付成功！', 'btn' => '返回', 'btn_url' => '/'));
                }
            }
        } else {
            //已经支付成功
            $this->load->view('pub/ts', array('msg' => '账单已支付成功！', 'btn' => '返回', 'btn_url' => '/'));
        }

    }

    function _do_pay($bill_id)
    {
        //订单不存在 发起支付
        $q = $this->db->get_where('bill', array('bill_id' => $bill_id));
        $bill = $q->row_array(0);

        $this->db->select('sp_name');
        $title = '商务订单-' . $bill_id;
        //计算需要提交的金额 判断是否使用金币
        $je = 0;
        if ($bill['use_jb'] == 1) {
            $ye = $this->pub->get_jb();
            if ($ye > $bill['je'] || $ye == $bill['je']) {
                $id = $this->pub->jb($je, -2, 1, $title, $bill['mid'], $bill['bill_id']);
                $this->db->update('bill', array('zfzt' => 2, 'state' => 1), array('bill_id' => $bill_id));
                $ts['sfzf'] = 1;
            } else {
                $je = $bill['je'] - $ye;
            }
        } else {
            $je = $bill['je'];
        }
        if ($je) {

            $q = $this->db->get_where('member', array('mid' => $this->session->userdata('mid')));
            $m = $q->row_array(0);


            //看看是否有支付的openid
            $openid = $this->pay->get_pay_openid($this->session->userdata('mid'), $bill_id);


            //使用统一支付接口
            $unifiedOrder = new UnifiedOrder_pub();

            $unifiedOrder->setParameter("body", $title);
            //商品描述
            $unifiedOrder->setParameter("out_trade_no", $bill_id);
            //商户订单号
            $unifiedOrder->setParameter("total_fee", $je * 100);
            //总金额
            $unifiedOrder->setParameter("notify_url", WX_NOTIFY_URL);
            //通知地址

            $unifiedOrder->setParameter("time_start", date('YmdHis'));
            //交易起始时间
            $unifiedOrder->setParameter("time_expire", date('YmdHis', (@mktime() + 600)));
            //交易结束时间
            if ($this->input->get('zflx') == 'app') {
                $unifiedOrder->setParameter("trade_type", "APP");
            } else {
                $unifiedOrder->setParameter("openid", $openid);
                $unifiedOrder->setParameter("trade_type", "JSAPI");
            }

            //交易类型

            $prepay_id = $unifiedOrder->getPrepayId();

            $jsApi = new JsApi_pub();
            $jsApi->setPrepayId($prepay_id);

            $ts['js'] = $jsApi->getParameters();
            $this->load->view('shop/ddzf', $ts);

        } else {
            //支付金额为0
            $this->load->view('pub/ts', array('msg' => '账单异常！', 'btn' => '返回', 'btn_url' => '/'));
        }
    }

    function bk($zflx = 'js')
    {
        $_GET['zflx'] = $zflx;
        include_once(FCPATH . APPPATH . 'third_party' . DS . 'wx' . DS . "WxPayPubHelper.php");
        //使用通用通知接口
        $notify = new Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);

        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL");
            //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败");
            //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS");
            //设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                $this->db->insert('zf_log', array('mktime' => @mktime(), 'log' => "【通信出错】:\n" . $xml . "\n"));
                //此处应该更新一下订单状态，商户自行增删操作
            } elseif ($notify->data["result_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                $this->db->insert('zf_log', array('mktime' => @mktime(), 'log' => "【业务出错】:\n" . $xml . "\n"));
            } else {
                //此处应该更新一下订单状态，商户自行增删操作
                $this->db->insert('zf_log', array('mktime' => @mktime(), 'log' => "【支付成功】:\n" . $xml . "\n"));
                $this->_do_zf($notify->data);
            }
        }

    }

    function _do_zf($notify)
    {
        //保证程序执行完成
        ignore_user_abort(TRUE);
        $q = $this->db->get_where('bill', array('bill_id' => $notify['out_trade_no']));
        $bill = $q->row_array(0);
        /*
        if ($bill['je'] > 390) {
            $this -> db -> update('member', array('type' => 3, 'tuan_state' => 1), array('mid' => $bill['mid']));
        } else {
            $this -> db -> update('member', array('type' => 3), array('mid' => $bill['mid']));
        }*/


        if ($bill['state'] == 0) {
            $da['trade_mode'] = $notify['trade_mode'];
            $da['trade_state'] = $notify['trade_state'];
            $da['partner'] = $notify['partner'];
            $da['bank_type'] = $notify['bank_type'];
            $da['bank_billno'] = $notify['bank_billno'];
            $da['total_fee'] = $notify['total_fee'] / 100;
            $da['fee_type'] = $notify['fee_type'];
            $da['notify_id'] = $notify['notify_id'];
            $da['transaction_id'] = $notify['transaction_id'];
            $da['out_trade_no'] = $notify['out_trade_no'];
            $da['attach'] = serialize($notify['attach']);
            $da['time_end'] = $notify['time_end'];
            $da['transport_fee'] = $notify['transport_fee'];
            $da['product_fee'] = $notify['product_fee'];
            $da['discount'] = $notify['discount'];
            $da['mktime'] = mktime();
            $this->db->insert('zf', $da);

            //获取账单信息
            $q = $this->db->get_where('bill_item', array('bill_id' => $da['out_trade_no']));
            $title = '';
            $lq = 0;
            foreach ($q->result_array() as $v) {
                $title .= $v['sp_name'] . ' ';
                $lq += $v['sp_lq'] * $v['numb'];
            }

            $id = $this->pub->jb($da['total_fee'], 1, 1, $title, $bill['mid'], $bill['bill_id']);

            if ($title == '充值 ') {
                //修改订单状态
                $this->db->update('bill', array('is_wxzf' => 1, 'zfzt' => 2, 'state' => 3), array('bill_id' => $da['out_trade_no']));
            } else {
                //修改订单状态
                $type = -2;
                if ($bill['is_jp'] == 2) {
                    $type = -4;
                }
                if ($bill['is_jp'] == 3) {
                    $type = -3;
                }
                $id = $this->pub->jb($bill['je'], $type, 1, $title, $bill['mid'], $bill['bill_id']);

                //虚拟商品发货 5是社区 6是购买社区 68是红包活动  全部商品立即发货
                if (1) {
                    $this->db->update('bill', array('is_wxzf' => 1, 'zfzt' => 2, 'state' => 1), array('bill_id' => $da['out_trade_no']));
                    $this->pub->send_jl($bill['mid'], $bill['bill_id']);
                } else {
                    $this->db->update('bill', array('is_wxzf' => 1, 'zfzt' => 2, 'state' => 1), array('bill_id' => $da['out_trade_no']));
                }

            }

            //推荐奖励 收货的时候更新
            $this->db->select('openid,mid,tj_mid,nickname');
            $q = $this->db->get_where('member', array('mid' => $bill['mid']));
            $m = $q->row_array(0);

            $this->pub->send_zd_text($m['openid'], '您购买的' . $title . '（￥' . $bill['je'] . '），支付成功！');

        }
    }

    function get_back()
    {
        include_once(FCPATH . APPPATH . 'third_party' . DS . 'wx' . DS . "WxPayPubHelper.php");
        //判断是否已经支付
        $orderQuery = new OrderQuery_pub();
        $orderQuery->setParameter("out_trade_no", $this->input->post('bill_id'));
        $orderQueryResult = $orderQuery->getResult();

        if ($orderQueryResult['trade_state'] == 'NOTPAY') {
            $da['type'] = 2;
        } else {
            if ($orderQueryResult['out_trade_no']) {
                $q = $this->db->update('bill', array('state' => 0), array('bill_id' => $this->input->post('bill_id')));
                $this->_do_zf($orderQueryResult);
                $da['type'] = 1;
            } else {
                $da['type'] = 2;
            }
        }
        echo json_encode($da);
    }

    private function getRedis()
    {
        static $redis;
        if (empty($redis)) {
            $redis = new Redis();
            $redis->connect('r-bp12adb5da21cc44.redis.rds.aliyuncs.com', 6379);
            $redis->auth('Pan123456');
        }
        return $redis;
    }

    //支付完成后的回调
    function _app_back()
    {

    }

}

?>
